<?php
/**
 * Created by lzl
 * Date: 2021 2021/9/18
 * Time: 10:55
 */
namespace App\Forms;


use App\Exceptions\RequestException;
use App\Models\Express;
use App\Utils\Express as ExpressUtils;
use App\Models\OrderExpress;
use Illuminate\Database\Query\Builder;

class ExpressForms extends BaseForm
{

    /**
     * 获取物流信息
     * @param $validated
     * @return mixed
     */
    public function getExpressList($validated = [])
    {
        $list = Express::where(function ($q) use ($validated) {
            /**
             * @var Builder $q
             */
            if (isset($validated['status']) && $validated['status']) {
                $q->where('status', $validated['status']);
            }

            return $q;
        })->page(function ($q) use ($validated) {

            if (isset($validated['page']) && isset($validated['limit'])) {
                $q->page($validated['page'], $validated['limit']);
            }

            return $q;
        })
            ->orderBy('id', 'asc')
            ->get();
        return $list;
    }


    /**
     * 更新快递
     * @param $validated
     * @return bool|int
     */
    public function editExpress($validated)
    {
        return Express::whereKey($validated['id'])->update($validated);
    }



    /**
     * 添加|更新快递信息
     * @param $arr
     * @return OrderExpress|\Illuminate\Database\Eloquent\Model
     */
    public function createOrderExpress($arr)
    {
        $arr['express_name'] = Express::find($arr['express_id'])->name;

        return OrderExpress::updateOrCreate(['order_id' => $arr['order_id']], $arr);
    }


    /**
     * 订单快递信息
     * @param $oid
     * @return OrderExpress|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getOrderExpress($oid)
    {
        return OrderExpress::where('order_id', $oid)->firstOrNew();
    }


    /**
     * 更新物流信息
     * @param $oid
     * @return bool
     * @throws RequestException
     */
    public function updateOrderExpress($oid)
    {
        $orderExpress = $this->getOrderExpress($oid);

        if($orderExpress->order_id && $orderExpress->express_sn && $orderExpress->express_id){

            $express = Express::find($orderExpress->express_id);

            $deliver               = new ExpressUtils();
            $deliver->express_sn   = $orderExpress->express_sn;
            $deliver->shipper_code = $express->code;

            $res = $deliver->search();

            if($res['Success']){
                $orderExpress->update([
                    'status' => $res['State'],
                    'express_details' => json_encode($res['Traces'],JSON_UNESCAPED_UNICODE)
                ]);
            }

            return true;
        }

        throw new RequestException('暂无物流信息');
    }
}